import sys,io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
import time
import requests
#from lxml import etree
from bs4 import BeautifulSoup
import pymysql
from random import randint, sample

def generate_front_num():

    front_balls = [x for x in range(1, 36)]

    selected_balls = sorted(sample(front_balls, 5))

    #print(selected_balls)

    return str(selected_balls)

def generate_back_num():

    back_ball = [y for y in range(1,13)]

    selected_backball = sorted(sample(back_ball, 2))

    #print(selected_backball)

    return str(selected_backball)

def generate_date():

    lottery_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))

    return lottery_date

def issue_number():
    
    url = 'http://kaijiang.500.com/shtml/dlt/'
    response = requests.get(url).text
    soup = BeautifulSoup(response, 'lxml')
    issue = soup.select('tr')[4].select('strong')[0].text
    #print(issue)
    return issue


def save_to_database():

    database = pymysql.connect(host='localhost', user='root', passwd='', db='lottery', charset='utf8')
    cursor = database.cursor()
    #check the issue info in database
    cursor.execute('select issue from dlt_my')
    issue_db = cursor.fetchall()
    list_issue_db = list(issue_db)
    #print(list_issue_db)
    
    # next issue should +1
    issue = int(issue_number()) + 1

    #check if next issue had already insert to database
    if str(issue) == list(list_issue_db[-1])[0]:
        print('已经随机过本期号码,随机号码为： ')

        cursor.execute('select front from dlt_my where issue='+str(issue))
        front_db = cursor.fetchone()
        print('前区： '+list(front_db)[0])
        
        cursor.execute('select back from dlt_my where issue='+str(issue))    
        back_db = cursor.fetchone()
        print('后区： '+list(back_db)[0])
        
        print('期号： '+str(issue))
        cursor.close()
    else:
        front_ball = generate_front_num()
        back_ball = generate_back_num()
        print('本期随机号码为：')
        print('前区： '+ front_ball)
        print('后区： '+ back_ball)
        print('期号： '+ str(issue))
    
        #insert to database
        insert_DB = "insert into dlt_my " +"(issue,front,back) values(%s,%s,%s)"
        values = (issue,front_ball,back_ball)

        cursor.execute(insert_DB,values)
        cursor.close()


    cursor.close()
    database.commit()
    database.close()


def main():
    #wechat()
    #get_info()
    save_to_database()
    #generate_front_num()
    #generate_back_num()
    #issue_number()

if __name__ == '__main__':
    main()
